package cn.eastseven.demo.netty.client;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import org.springframework.stereotype.Component;

import cn.eastseven.demo.netty.common.Header;
import cn.eastseven.demo.netty.common.MessageType;
import cn.eastseven.demo.netty.common.NettyMessage;

@Component
@Sharable
public class LoginAuthReqHandler extends ChannelHandlerAdapter {

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		NettyMessage loginRequest = buildLoginRequest();
		ctx.writeAndFlush(loginRequest);
		System.out.println("channelActive: "+loginRequest);
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println("channelRead: " + msg);
		NettyMessage message = (NettyMessage) msg;
		if(message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP) {
			System.out.println("Received from server response: " + message);  
		} else {
			System.out.println("Received from server response: " + msg);
		}
		ctx.fireChannelRead(msg);
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.fireExceptionCaught(cause);
		//ctx.close();
	}
	
	private NettyMessage buildLoginRequest() {
		NettyMessage req = new NettyMessage();
		Header header = new Header();
		header.setType(MessageType.LOGIN_REQ);
		req.setHeader(header);
		//req.setBody("LoginRequest");
		return req;
	}
}
